package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

@Service
public class FileService {
    @Autowired
    ResourceLoader resourceLoader;

    public void GetFile(String filename, String path, HttpServletResponse response) throws Exception{
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        Resource resource = resourceLoader.getResource("classpath:"+path);
        response.setContentType("application/msword");
        response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.addHeader("charset", "utf-8");
        response.addHeader("Pragma", "no-cache");
        response.addHeader("Content-Disposition","attachment;fileName=" +new String(filename.getBytes("UTF-8"),"iso-8859-1"));
        inputStream = resource.getInputStream();
        servletOutputStream = response.getOutputStream();
        org.apache.tomcat.util.http.fileupload.IOUtils.copy(inputStream,servletOutputStream);
        response.flushBuffer();
        servletOutputStream.close();
        inputStream.close();
    }
}
